<template>
  <el-form label-width="100px" :model="spuInfo" :rules="spuRules" ref="spuFormRef">
    <el-form-item label="SPU名称" prop="spuName">
      <el-input placeholder="SPU名称" v-model="spuInfo.spuName"></el-input>
    </el-form-item>
    <el-form-item label="品牌" prop="tmId">
      <el-select placeholder="请选择品牌" v-model="spuInfo.tmId">
        <el-option v-for="trademark in trademarkList" :label="trademark.tmName" :value="trademark.id" :key="trademark.id" />
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述" prop="description">
      <el-input type="textarea" v-model="spuInfo.description" :rows="3"></el-input>
    </el-form-item>
    <!-- <el-form-item label="SPU图片" prop="spuImageList"> -->
    <el-form-item label="SPU图片" prop="spuImageList">
      <el-upload v-model:file-list="spuInfo.spuImageList"  :action="`${BASE_URL}/admin/product/upload`" list-type="picture-card" :on-remove="handleRemove" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
        <el-icon>
          <Plus />
        </el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
    </el-form-item>
    <el-form-item label="销售属性" prop="spuSaleAttrList">
      <!-- <el-select v-model="spuInfo.spuSaleAttr" :placeholder="`还剩下${baseSaleAttrList.length}个未选择`"> -->
      <el-select v-model="spuInfo.spuSaleAttr" :placeholder="`还剩下${filterBaseSaleAttrList.length}个未选择`">
        <el-option v-for="baseSaleAttr in filterBaseSaleAttrList" :label="baseSaleAttr.name" :value="baseSaleAttr.name" :key="baseSaleAttr.id" />
      </el-select>
      <el-button type="primary" :disabled="!spuInfo.spuSaleAttr" @click="toAddSpuSaleAttr">添加销售属性</el-button>

      <el-table border :data="spuInfo.spuSaleAttrList">
        <el-table-column label="序号" width="80px" type="index" align="center"></el-table-column>
        <el-table-column label="属性名" prop="saleAttrName" width="120px"></el-table-column>
        <el-table-column label="属性值名称列表">
          <template v-slot="{row}">
            <el-tag v-for="tag in row.spuSaleAttrValueList" :key="tag" class="mx-1" closable :disable-transitions="false" @close="handleClose(row,tag)">
              {{ tag.saleAttrValueName }}
            </el-tag>
            <el-input v-if="row.inputVisible" ref="InputRef" v-model="inputValue" class="ml-1 w-20" style="width:100px" size="small" @keyup.enter="handleInputConfirm(row)" @blur="handleInputConfirm(row)" />
            <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput(row)">
              + New
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{row,$index}">
            <el-popconfirm confirm-button-text="确定" cancel-button-text="取消" :icon="InfoFilled" icon-color="#626AEF" title="真的确定要删除此条数据么?" @confirm="deleteAttr($index)">
              <template #reference>
                <el-button title="删除" type="danger" size="small" :icon="Delete" />
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitSpuForm(spuFormRef)">保存</el-button>
      <el-button @click="emits('setShowStatus',ShowStatus.SPU_LIST)">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
export default {
  name:'SpuForm'
}
</script>

 <script lang="ts" setup>
import {ref,onMounted,reactive,computed,nextTick} from 'vue'
import { Plus,Delete,InfoFilled } from '@element-plus/icons-vue'
import { ElMessage, ElInput, type UploadFile} from 'element-plus'
import type { UploadProps, UploadUserFile,FormInstance, FormRules  } from 'element-plus'
import { reqGetAllTrademarkListData,reqGetAllBaseSaleAttrListData, reqSaveSpuInfoData,reqGetSpuImageListData,reqGetSpuSaleAttrListData,reqUpdateSpuInfoApi  } from '@/api/product/spu'
import { ShowStatus } from '../types'
import { useCategoryListStore } from '@/stores/categoryList';
const categoryStore = useCategoryListStore();

const emits = defineEmits(['setShowStatus']) // 接收自定义事件
const props = defineProps(['currentSpuInfo'])
//定义spu
const spuInfo = reactive({
  spuName:'', //spu名称
  tmId:'',  //品牌对应的id
  description:'', //spu描述
  spuImageList:[], //上传的图片`````````````````````````````````````````````````````````````````````````````````````````````````````
  spuSaleAttrList:[],//销售属性
  category3Id:-1,
  spuSaleAttr:'' ,//销售属性名
  ...props.currentSpuInfo //展开待编辑的数据
  
})

// 定义上传图片的数据
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const fileList = ref<UploadUserFile>([])
// 上传图片地址，会从.env.development中加载
const BASE_URL = import.meta.env.VITE_API_URL



//1.定义品牌列表和销售属性的数据
const trademarkList = ref([])
const baseSaleAttrList = ref([])


//属性值tag标签
const inputValue = ref('')
const dynamicTags = ref(['Tag 1', 'Tag 2', 'Tag 3'])
const inputVisible = ref(false)
const InputRef = ref<InstanceType<typeof ElInput>>()

const spuFormRef = ref<FormInstance>()
  const formSize = ref('default')


  //添加spu数据的校验规则
  const spuRules = reactive<FormRules>({
    spuName:[
      {required: true, message:'请填写Spu名称',trigger:'blur'},
      {min: 2, max:10,message:'长度在2-10个字符之间', trigger:'blur'}
    ],
    tmId:[{
      required: true, 
      message:'请选择一个品牌',
      trigger:'change'
    }],
    description:[{
      required: true, message:'请填写Spu描述',trigger:'blur'
    }],
    spuImageList:[{
      required: true, type:'array', message:'请至少上传一张图片',trigger:'change'
    }],
    spuSaleAttrList: [{ required: true, message: '请至少添加一个属性', type: 'array', trigger: 'click' }]
  })



//2.同时发送品牌列表和销售属性两个请求
onMounted(async() => {
   try{

      const { id } = spuInfo
      let promises = [reqGetAllTrademarkListData(),reqGetAllBaseSaleAttrListData()]
      // const [responseTrademarkList,responseBaseSaleAttrList]=await Promise.all([reqGetAllTrademarkListData(),reqGetAllBaseSaleAttrListData()])
      // console.log('111',responseTrademarkList,responseBaseSaleAttrList);
      if(id){
        //有id就是编辑修改
        promises = promises.concat([reqGetSpuImageListData(id),reqGetSpuSaleAttrListData(id)])
      }

      const [responseTrademarkList,responseBaseSaleAttrList,responseSpuImageList,responseSpuSaleAttrList] = await Promise.all(promises)
      
      trademarkList.value = responseTrademarkList
      baseSaleAttrList.value = responseBaseSaleAttrList

      if (responseSpuImageList && responseSpuSaleAttrList) {
      // spuInfo.spuImageList = responseSpuImageList
      spuInfo.spuImageList = responseSpuImageList.map(item=>{
        return{
          ...item,
          name: item.imgName,
          url:item.imgUrl
        }
      })
      spuInfo.spuSaleAttrList = responseSpuSaleAttrList
    }

   }catch(error){
    ElMessage.error('获取属性失败')
   }
})

// 上传图片的函数
//上传成功后，收集图片链接
const handleAvatarSuccess: UploadProps['onSuccess'] = (response:any,uploadFile:UploadFile,uploadFiles:UploadFiles) => {
  console.log(response,uploadFile);
  
    // spuInfo.spuImageList.push({
    //   imgName: uploadFile.name,
    //   imgUrl: response.data
    // })
    spuInfo.spuImageList = uploadFiles
    // 清空校验规则
    spuFormRef.value!.clearValidate(['spuImageList'])
}

//上传图片前的校验
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  const imgArr = ['image/jpeg','image/png']
  if(!imgArr.includes(rawFile.type)){
    ElMessage.error('图片格式只能是jpg,jpeg,png,请重选')
    return false
  }else if(rawFile.size /1024/1024 > 2){
    ElMessage.error('图片大小不能超过2M,请重新选择')
    return false
  }
  return true
}

//删除上传的图片数据
const handleRemove: UploadProps['onRemove'] =(uploadFile,uploadFiles)=>{
  spuInfo.spuImageList = uploadFiles.map(item=>{
    // return{
    //     imgName:item.name,
    //     imgUrl:item.response.data
    // }
    //赋值，修正删除照片时的问题
    spuInfo.spuImageList = uploadFiles
  })
}

//添加销售属性
const toAddSpuSaleAttr =()=>{
  const spuSaleAttrList = spuInfo.spuSaleAttrList
  if(spuSaleAttrList.length && spuSaleAttrList.some(item=>item.spuSaleAttrValueList.length === 0 )){
    ElMessage.warning('属性值不能为空，请添加')
    return
  }


  //销售属性的id
  const id = baseSaleAttrList.value.find(item=>item.name===spuInfo.spuSaleAttr).id
  //添加销售属性
  spuInfo.spuSaleAttrList.push({
    baseSaleAttrId: id,
    saleAttrName: spuInfo.spuSaleAttr,
    spuSaleAttrValueList:[],
    inputVisible: false // 输入框和tag切换
  })
  spuInfo.spuSaleAttr='' //清空下拉框选项
  spuInfo.spuSaleAttr='' //清空输入框的值
  spuFormRef.value!.clearValidate(['spuSaleAttrList']) //清空校验规则
}

//计算属性 选取销售属性移除效果
const filterBaseSaleAttrList = computed(()=>{
  return baseSaleAttrList.value.filter(baseSale=>{
    return !spuInfo.spuSaleAttrList.find(item=>baseSale.name===item.saleAttrName)
  })
})

//删除当前属性
const deleteAttr = (index: number)=>{
  spuInfo.spuSaleAttrList.splice(index,1)
}



//销售属性值tag标签的操作

//删除销售属性值
const handleClose = (row,tag) => {
  // dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
  row.spuSaleAttrValueList.splice(row.spuSaleAttrValueList.indexOf(tag),1)
}

//显示输入框
const showInput = (row) => {
  row.inputVisible = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}

const handleInputConfirm = (row) => {
  if (inputValue.value) {
    //判断销售属性值是否重复
    if(row.spuSaleAttrValueList.find(item=>item.saleAttrValueName===inputValue.value)){
      ElMessage.warning('此属性值已添加过，请换一下')
      return
    }

    const id = baseSaleAttrList.value.find(item=>item.name===row.saleAttrName).id

    row.spuSaleAttrValueList.push({
      baseSaleAttrId:id,
      saleAttrValueName: inputValue.value,
      // saleAttrName: spuInfo.spuSaleAttr
      saleAttrName: row.saleAttrName
    })
  }
  row.inputVisible= false
  inputValue.value = ''
}

//点击保存按钮,提交前的校验
const submitSpuForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) =>{
    if (valid) {
      const spuSaleAttrList = spuInfo.spuSaleAttrList;

      if (spuSaleAttrList.length && !spuSaleAttrList.every(item => item.spuSaleAttrValueList.length)) {
        ElMessage.warning('属性值为空,请检查或添加...');
        return;
      }

         // 提取一下图片的内容，处理图片的属性问题
         spuInfo.spuImageList = spuInfo.spuImageList.map(item => {
        return {
          // imgName: item.name,
          // imgUrl: item.response.data
          imgName: item.imgName ? item.imgName : item.name,
          imgUrl: item.imgUrl ? item.imgUrl : item.response.data
        }
      })
        //发送请求去添加spuInfo
      spuInfo.category3Id = categoryStore.category3Id as number;

      //通过id判断是编辑 还是 单纯保存 提交
      if(spuInfo.id){
        await reqUpdateSpuInfoApi(spuInfo)
      }else{
        await reqSaveSpuInfoData(spuInfo);
      }

      

      // 提示一下用户
      ElMessage.success('添加spu对象成功了...');
      // 跳转到列表页
      emits('setShowStatus', ShowStatus.SPU_LIST);
    } else {
      console.log('error submit!', fields)
    }
  })
}
   
</script>

<style>

</style>